package leetcode.code019.RemoveNthNodeFromEndofList;

import leetcode.helper.tree.ListNode;

/**
 * 两次遍历，数数
 *
 * @author Max
 * @date 2021年8月16日
 * @description
 */
public class Solution2 extends RemoveNthNodeFromEndofList {

	@Override
	public ListNode removeNthFromEnd(ListNode head, int n) {
		int total = 0;
		ListNode p = head;
		while (p != null) {
			total++;
			p = p.next;
		}
		int aim = total - n;
		if (aim - 1 >= 0) {
			p = head;
			while (aim != 1) {
				p = p.next;
				aim--;
			}
			p.next = p.next.next;
		} else {
			head = head.next;
		}
		return head;
	}

	public static void main(String[] args) {
		RemoveNthNodeFromEndofList so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
//		so.debug4();
	}

}
